/*
 * Powered By [rapid-framework]
 * Csdn Code: generate simple CRUD code in single table.
 * Since 2015 - 2017
 */

BUI.use('common/page');
BUI.use(['common/search', 'bui/overlay', 'bui/grid', 'bui/data', 'bui/form'],
    function (Search, Overlay, Grid, Data, Form) {
      var appConditionEnum = {
        '0': 'xxxxx',
        '1': 'xxxxx',
        '2': 'xxxxx',
        '3': 'xxxxx'
      };
      var conditionTypeEnum = {
        '1': '条件控制',
        '2': 'banner控制'
      };
      var switchEnum = {
        'false': '失效',
        'true': '有效'
      };
      // 查询表单
      var form = new Form.Form({
        srcNode: '#searchForm'
      }).render();
      // 定义表头
      columns = [
        {
          title: '主键ID',
          dataIndex: 'appConditionId',
          visible: false
        },
        {
          title: 'app版本ID',
          dataIndex: 'appId',
          visible: false
        },
        {
          title: '条件类型',
          dataIndex: 'conditionType',
          elCls: 'center',
          width: 150,
          editor: {
            xtype: 'select',
            items: conditionTypeEnum,
            rules: {
              required: [true, '条件类型控制不能为空!']
            }
          },
          renderer: BUI.Grid.Format
          .enumRenderer(conditionTypeEnum)
        },
        {
          title: 'APP描述',
          dataIndex: 'appDesc',
          elCls: 'center',
          width: 200,
          editor: {
            xtype: 'text',
            rules: {
              required: [true, 'APP描述不能为空!']
            }
          }
        },
        {
          title: '条件值',
          dataIndex: 'conditionValues',
          elCls: 'center',
          width: 120,
          editor: {
            xtype: 'text',
            rules: {
              required: [true, '条件值不能为空!']
            }
          }
        },
        {
          title: '状态',
          dataIndex: 'conditionStatus',
          elCls: 'center',
          width: 120,
          editor: {
            xtype: 'select',
            items: switchEnum,
            rules: {
              required: [true, '状态不能为空!']
            }
          },
          renderer: BUI.Grid.Format
          .enumRenderer(switchEnum)
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          elCls: 'center',
          width: 150,
          editor: {
            xtype: 'date',
            datePicker: {
              showTime: true
            },
            rules: {
              required: [true, '最后创建时间不能为空!']
            }
          },
          renderer: BUI.Grid.Format.datetimeRenderer
        },
        {
          title: '最后更新时间',
          dataIndex: 'updateTime',
          elCls: 'center',
          width: 150,
          editor: {
            xtype: 'date',
            datePicker: {
              showTime: true
            },
            rules: {
              required: [true, '最后最后更新时间不能为空!']
            }
          },
          renderer: BUI.Grid.Format.datetimeRenderer
        },
        {
          title: '操作',
          elCls: 'center',
          width: 100,
          renderer: function (value, obj) {
            return '<span class="grid-command btn-edit">编辑</span>';
          }
        }];
      // 行编辑
      var editing = new Grid.Plugins.RowEditing({
            triggerCls: 'btn-edit',
            triggerSelected: false

          }),
          // 获取数据
          store = new BUI.Data.Store({
            url: 'listAppCondition?field=createTime&direction=desc',
            pageSize: 20,
            autoLoad: true,
            remoteSort: true
          });
      // 获取表格对象
      gridCfg = Search.createGridCfg(columns, {
        plugins: [editing, Grid.Plugins.CheckSelection],
        tbar: { // 添加、删除
          items: [{
            btnCls: 'button button-small',
            text: '<i class="icon-plus"></i>添加',
            listeners: {
              'click': addFunction
            }
          }, {
            btnCls: 'button button-small',
            text: '<i class="icon-refresh"></i>刷新',
            listeners: {
              'click': refreshFunction
            }
          }, {
            btnCls: 'button button-small',
            text: '<i class="icon-remove"></i>删除',
            listeners: {
              'click': delFunction
            }
          }]
        },
      });
      // 触发编辑
      editing.on('editorshow', function (ev) {
        var editor = editing.get('curEditor');
        editor.set('errorAlign', {
          points: ['br', 'tr'],
          offset: [0, 10]
        });
      });
      // 编辑提交
      editing.on('accept', function (ev) {
        var record = editing.get('record');
        var none = record["appConditionId"] === "";
        var saveUrl = none ? 'saveAppCondition' : 'updateAppCondition';
        var requestType = none ? 'POST' : 'PUT';
        jQuery.ajax({
          type: requestType,
          url: saveUrl,
          dataType: 'json',
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify(record),
          complete: function (data) {
            if (data.responseText == "success") { // 删除成功
              search.load();
            } else { // 删除失败
              BUI.Message.Alert('保存失败！');
            }
          }
        });
      });
      var dialog = new Overlay.Dialog({
        title: 'App条件筛选',
        width: 650,
        height: 450,
        //配置DOM容器的编号
        contentId: 'content',
        success: function () { //产品保存
          var d = {};
          var a = [];
          var f = false;
          var e = {
            type: '类型不能空！',
            value: '值不能为空!'
          };
          var t = $('#J_Form').serializeArray();
          $.each(t, function () {
            d[this.name] = this.value;
          });
          // console.log(JSON.stringify(d));
          $("#conditionTable").find("tr").each(function () {
            if ($(this).children('td').eq(0).find("input").is(':checked')) {
              var id = $(this).children('td').eq(1).html().trim();
              a.push(id);
            }
          });
          // console.log(a);
          if (a.length === 0) {
            alert("未选择选项");
          }
          d.ids = a;
          // alert(BUI.JSON.stringify(d));
          valid(d, e);

          function valid(d, e) {
            for (var key in d) {
              // console.log(key + ":" + d[key]);
              if (Array.isArray(d[key])) {
                for (var o in d[key]) {
                  valid(o, e);
                }
              }
              if (!d[key]) {
                f = true;
                alert(e[key]);
              }
            }
          }

          if (!f) {
            var saveUrl = 'batchInsertAppConditon';
            jQuery.ajax({
              type: 'POST',
              url: saveUrl,
              dataType: 'json',
              contentType: 'application/json;charset=UTF-8',
              data: BUI.JSON.stringify(d),
              complete: function (data) {
                if (data.responseText == "success") { // 保存成功
                  search.load();
                } else { // 删除失败
                  BUI.Message.Alert('保存失败！');
                }
              }
            });
            this.close();
          }

        }
      });

      // 添加记录
      function addFunction() {
        // store.addAt(newData, 0);
        // editing.edit(); // 添加记录后，直接编辑
        $("#conditionTable").empty();
        dialog.show();
      }

      // 删除选中的记录
      function delFunction() {
        var selections = grid.getSelection();
        delItems(selections);
        store.remove(selections);
      }

      // 刷新
      function refreshFunction() {
        search.load();
      }

      // 删除
      function delItems(items) {
        var ids = "";
        BUI.each(items, function (item) {
          ids += item.appConditionId + ",";
        });
        if (ids.length) {
          BUI.Message.Confirm('确认要删除选中的记录么？', function () {
            jQuery.ajax({
              type: 'DELETE',
              url: 'removeAppCondition?ids=' + ids,
              dataType: 'json',
              data: {},
              complete: function (data) {
                if (data.responseText == "success") { // 删除成功
                  search.load();
                } else { // 删除失败
                  BUI.Message.Alert('删除失败！');
                }
              }
            });
          }, 'question');
        }
      }

      // 查询
      search = new Search({
        store: store,
        autoSearch: true,
        gridCfg: gridCfg
      });
      grid = search.get('grid');
    });

//查询
function searchItem() {
  var d = {};
  var saveUrl = "";
  var pageSize = 50;
  //清空表格
  $("#conditionTable").empty();
  var t = $('#J_Form').serializeArray();
  // console.log(t);
  $.each(t, function () {
    d[this.name] = this.value;
  });
  // console.log(JSON.stringify(d));
  var type = d.type;
  // console.log(type);
  //BUI.JSON.stringify(d)
  type = parseInt(type);
  switch (type) {
    case 1:
      saveUrl = 'findAllVersion?field=versionId&start=0&limit={0}&pageIndex=0&direction=ASC'.replace("{0}",pageSize);
      $('#column1').html("版本号Id");
      $('#column2').html("版本名称");
      $('#column3').html("");
      break;
    case 2:
      saveUrl = 'findAllBanner?field=bannerId&start=0&limit={0}&pageIndex=0&direction=ASC'.replace("{0}",pageSize);
      $('#column1').html("bannerId");
      $('#column2').html("banner类型");
      $('#column3').html("banner图片");
      break;
    case 3:
      saveUrl = 'findAllProduct?field=productId&start=0&limit={0}&pageIndex=0&direction=ASC&isTechnical=0'.replace("{0}",pageSize);
      $('#column1').html("产品Id");
      $('#column2').html("产品名称");
      $('#column3').html("产品类型");
      break;
    case 4:
      saveUrl = 'findAllSpecialProduct?field=specialId&start=0&limit={0}&pageIndex=0&direction=ASC&conditionStatus=1'.replace("{0}",pageSize);
      $('#column1').html("产品Id");
      $('#column2').html("快贷Id");
      $('#column3').html("产品名称");
      break;
  }

  function getDesc(type) {
    var desc = "";
    switch (type) {
      case 1:
        desc = "现金";
        break;
      case 2:
        desc = "还信用卡";
        break;
      case 3:
        desc = "购物消费";
        break;
    }
    return desc;
  }

  jQuery.ajax({
    type: 'POST',
    url: saveUrl,
    dataType: 'json',
    contentType: 'application/json;charset=UTF-8',
    data: {},
    complete: function (data) {
      if (data.responseText) { // 保存成功
        // console.log(data);
        // console.log(typeof data);
        data = JSON.parse(data.responseText);
        var html = "";
        switch (type) {
          case 1://版本
            //清空表格
            $("#conditionTable").empty();
            var rows = data.rows;
            var casetotalpage = data.results;
            $('.M-box').pagination({
              totalData: casetotalpage,
              pageCount: getPageCount(
                  {'totalData': casetotalpage, 'showData': pageSize, 'pageCount': 9}),
              jump: true,
              showData: pageSize,
              coping: true,
              callback: function (api) {
                //这里写ajax方法，url
                var data = {};
                var currentPage = api.getCurrent();
                // console.log(currentPage);
                var start = (currentPage - 1) * pageSize;
                $.getJSON(
                    'findAllVersion?field=versionId&start={0}&limit={2}&pageIndex={1}&direction=ASC'.replace(
                        "{0}", start).replace("{1}", currentPage-1).replace("{2}",pageSize), data,
                    function (json) {
                      $("#conditionTable").empty();
                      // console.log(json);
                      var rows = json.rows;
                      var html = "";
                      debugger;
                      BUI.each(rows, function (item, index) {
                        var trHtml = "       <tr>\n"
                            + "                  <td><input type=\"checkbox\"></td>\n"
                            + "                  <td >{0}</td>\n".replace("{0}",
                                item.versionId)
                            + "                  <td>{1}</td>\n".replace("{1}",
                                item.appName)
                            + "                  <td>{2}</td>\n".replace("{2}", "")
                            + "              </tr>";
                        html += trHtml;
                      });
                      $("#conditionTable").append(html);
                    });
              }
            });
            BUI.each(rows, function (item, index) {
              var trHtml = "       <tr>\n"
                  + "                  <td><input type=\"checkbox\"></td>\n"
                  + "                  <td >{0}</td>\n".replace("{0}",
                      item.versionId)
                  + "                  <td>{1}</td>\n".replace("{1}",
                      item.appName)
                  + "                  <td>{2}</td>\n".replace("{2}", "")
                  + "              </tr>";
              html += trHtml;
            });
            break;
          case 2://banner控制
            //清空表格
            $("#conditionTable").empty();
            var rows = data.rows;
            var casetotalpage = data.results;
            $('.M-box').pagination({
              totalData: casetotalpage,
              pageCount: getPageCount(
                  {'totalData': casetotalpage, 'showData': pageSize, 'pageCount': 9}),
              jump: true,
              showData: pageSize,
              coping: true,
              callback: function (api) {
                //这里写ajax方法，url
                var data = {};
                var currentPage = api.getCurrent();
                // console.log(currentPage);
                var start = (currentPage - 1) * pageSize;
                $.getJSON(
                    'findAllBanner?field=bannerId&start={0}&limit={2}&pageIndex={1}&direction=ASC'.replace(
                        "{0}", start).replace("{1}", currentPage-1).replace("{2}",pageSize), data,
                    function (json) {
                      $("#conditionTable").empty();
                      // console.log(json);
                      var rows = json.rows;
                      var html = "";
                      BUI.each(rows, function (item, index) {
                        var trHtml = "       <tr>\n"
                            + "                  <td><input type=\"checkbox\"></td>\n"
                            + "                  <td >{0}</td>\n".replace("{0}",
                                item.bannerId)
                            + "                  <td>{1}</td>\n".replace("{1}",
                                item.bannerType)
                            + "                  <td>{2}</td>\n".replace("{2}",
                                item.bannerImg)
                            + "              </tr>";
                        html += trHtml;
                      });
                      $("#conditionTable").append(html);
                    });
              }
            });
            BUI.each(rows, function (item, index) {
              var trHtml = "       <tr>\n"
                  + "                  <td><input type=\"checkbox\"></td>\n"
                  + "                  <td >{0}</td>\n".replace("{0}",
                      item.bannerId)
                  + "                  <td>{1}</td>\n".replace("{1}",
                      item.bannerType)
                  + "                  <td>{2}</td>\n".replace("{2}",
                      item.bannerImg)
                  + "              </tr>";
              html += trHtml;
            });
            break;
          case 3://产品 这里需要分页
            //清空表格
            $("#conditionTable").empty();
            var rows = data.rows;
            var casetotalpage = data.results;
            $('.M-box').pagination({
              totalData: casetotalpage,
              pageCount: getPageCount(
                  {'totalData': casetotalpage, 'showData': pageSize, 'pageCount': 9}),
              jump: true,
              showData: pageSize,
              coping: true,
              callback: function (api) {
                //这里写ajax方法，url
                var data = {};
                var currentPage = api.getCurrent();
                // console.log(currentPage);
                var start = (currentPage - 1) * pageSize;
                $.getJSON(
                    'findAllProduct?field=productId&start={0}&limit={2}&pageIndex={1}&direction=ASC&isTechnical=0'.replace(
                        "{0}", start).replace("{1}", currentPage-1).replace("{2}",pageSize), data,
                    function (json) {
                      $("#conditionTable").empty();
                      // console.log(json);
                      var rows = json.rows;
                      var html = "";
                      BUI.each(rows, function (item, index) {
                        var trHtml = "       <tr>\n"
                            + "                  <td><input type=\"checkbox\"></td>\n"
                            + "                  <td >{0}</td>\n".replace("{0}",
                                item.productId)
                            + "                  <td>{1}</td>\n".replace("{1}",
                                item.productName)
                            + "                  <td>{2}</td>\n".replace("{2}",
                                getDesc(item.productType))
                            + "              </tr>";
                        html += trHtml;
                      });
                      $("#conditionTable").append(html);
                    });
              }
            });
            BUI.each(rows, function (item, index) {
              var trHtml = "       <tr>\n"
                  + "                  <td><input type=\"checkbox\"></td>\n"
                  + "                  <td >{0}</td>\n".replace("{0}",
                      item.productId)
                  + "                  <td>{1}</td>\n".replace("{1}",
                      item.productName)
                  + "                  <td>{2}</td>\n".replace("{2}",
                      getDesc(item.productType))
                  + "              </tr>";
              html += trHtml;
            });
            break;
          case 4://快贷
            //清空表格
            $("#conditionTable").empty();
            var rows = data.rows;
            var casetotalpage = data.results;
            $('.M-box').pagination({
              totalData: casetotalpage,
              pageCount: getPageCount(
                  {'totalData': casetotalpage, 'showData': pageSize, 'pageCount': 9}),
              jump: true,
              showData: pageSize,
              coping: true,
              callback: function (api) {
                //这里写ajax方法，url
                var data = {};
                var currentPage = api.getCurrent();
                // console.log(currentPage);
                var start = (currentPage - 1) * pageSize;
                $.getJSON(
                    'findAllSpecialProduct?field=specialId&start={0}&limit={2}&pageIndex={1}&direction=ASC&conditionStatus=1'.replace(
                        "{0}", start).replace("{1}", currentPage-1).replace("{2}",pageSize), data,
                    function (json) {
                      $("#conditionTable").empty();
                      // console.log(json);
                      var rows = json.rows;
                      var html = "";
                      BUI.each(rows, function (item, index) {
                        var trHtml = "       <tr>\n"
                            + "                  <td><input type=\"checkbox\"></td>\n"
                            + "                  <td >{0}</td>\n".replace("{0}",
                                item.productId)
                            + "                  <td>{1}</td>\n".replace("{1}",
                                item.specialId)
                            + "                  <td>{2}</td>\n".replace("{2}",
                                item.specialName)
                            + "              </tr>";
                        html += trHtml;
                      });
                      $("#conditionTable").append(html);
                    });
              }
            });
            BUI.each(rows, function (item, index) {
              var trHtml = "       <tr>\n"
                  + "                  <td><input type=\"checkbox\"></td>\n"
                  + "                  <td >{0}</td>\n".replace("{0}",
                      item.productId)
                  + "                  <td>{1}</td>\n".replace("{1}",
                      item.specialId)
                  + "                  <td>{2}</td>\n".replace("{2}",
                      item.specialName)
                  + "              </tr>";
              html += trHtml;
            });
            break;
        }
        $("#conditionTable").append(html);
        // search.load();
      } else { // 删除失败
        BUI.Message.Alert('保存失败！');
      }
    }
  });
  this.close();
}

//全选
function selectAll(obj) {
  if (obj.checked) {
    // console.log("selected");
    $("input[type='checkbox']").attr("checked", "true");
  } else {
    // console.log("unselected");
    $("input[type='checkbox']").removeAttr("checked");
  }
}

//反选
function unselect() {
  $("#conditionTable input[type='checkbox']").each(function () {
    if ($(this).attr("checked")) {
      $(this).removeAttr("checked");
    }
    else {
      $(this).attr("checked", "true");
    }
  })
}

function getPageCount(opts) {
  return opts.totalData && opts.showData ? Math.ceil(parseInt(opts.totalData)
      / opts.showData) : opts.pageCount;
}
